import json

from flask import render_template, request, redirect, url_for, flash, jsonify,session,make_response
from flask_bcrypt import generate_password_hash, check_password_hash

from . import views
from ..models.mysql import Mysql
from ..tools.markdown import convert_markdown
from ..tools.file import read_file_or_create, read_file
from ..tools import service
from ..tools.validate import validate_email, is_number


@views.route("/")
@views.route("/index")
def index():
    flash("233", "info")
    return render_template('index.html')


@views.route("/list")
def list():

    return render_template('list.html')


@views.route("/article")
def article():

    article = convert_markdown(read_file('./README.md'))

    return render_template('article.html', article=article)


@views.route("/archives")
def archives():

    return render_template('archives.html')


@views.route("/links")
def links():

    return render_template('links.html')


@views.route("/about")
def about():
    about_content = convert_markdown(read_file_or_create('about.md'))

    return render_template('about.html', about_content=about_content)


@views.route("/search")
def search():

    return render_template('search.html')


@views.route("/login",  methods=["GET", "POST"])
def login():
    if request.method == "POST":
        email = request.form.get("email")
        pwd = request.form.get("password")
        with Mysql(True) as conn:
            conn.cursor.execute(
                """SELECT * FROM admins WHERE `email`=%s;""", (email))
            res = conn.cursor.fetchone()
            if res and check_password_hash(res["password"], pwd):
                resp = make_response(redirect(url_for('views.admin')))
                service.login(res, resp)
                flash("登录后台成功。。", "success")
                return resp
                
            flash("邮箱或密码错误！！！！", "error")

    return render_template('login.html')


@views.route("/forget_password", methods=["GET", "POST"])
def forget_password():
    if request.method == "POST":
        email = request.form.get("email")
        if not validate_email(email):
            flash("邮箱错误！！", "error")
            return redirect(url_for("views.forget_password"))
        code = request.form.get("code")
        if not is_number(code) or session[email] != int(code):
            flash("验证码错误！！", "error")
            return redirect(url_for("views.forget_password"))

        pwd = request.form.get("password")
        if pwd:
            pwd = generate_password_hash(pwd)
            with Mysql(True) as conn:
                conn.cursor.execute("""UPDATE admins set `password`=%s WHERE `email`=%s;""", (pwd, email))
                flash("密码重置成功！", "success")
                return redirect(url_for('views.login'))
        flash("你莫不是来消遣洒家的？？？", "error")
    return render_template('forget_password.html')


@views.route("/forget_password_send_code", methods=["POST"])
def forget_password_send_code():
    email = json.loads(request.data)['email']

    with Mysql() as conn:
        conn.cursor.execute(
            """SELECT * FROM admins WHERE `email`=%s""", (email,))
        res = conn.cursor.fetchone()
        if res:
            if service.sendCode(email):
                return jsonify({
                    'code': 200,
                    'data': True
                })
                
    return jsonify({
        'code': -1,
        'data': False
    })
